package org.example.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.example.bean.Result;
import org.example.util.JwtUtil;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/9/10
 * Email haijunzhou@hnit.edu.cn
 */
@Component
@Slf4j
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        // 后置拦截
        return "post";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext cxt = RequestContext.getCurrentContext();
        HttpServletRequest request = cxt.getRequest();
        String servletPath = request.getServletPath();
        return "/cloud-user/login".equals(servletPath)||
                "/user/login".equals(servletPath)||
                "/cloud-user/mobileLogin".equals(servletPath)||
                "/cloud-user/updateuser".equals(servletPath);
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext cxt = RequestContext.getCurrentContext();
        InputStream inputStream = cxt.getResponseDataStream();
        byte[] data = new byte[1024];
        try {
            int count = inputStream.read(data);
            String json = new String(data, 0, count);
            ObjectMapper objectMapper = new ObjectMapper();
            Result result = objectMapper.readValue(json, Result.class);
            if(result.getCode() == 1){
                // 登录成功 用户信息 编码成 jwt => 写入响应头 Authorization
                String s = objectMapper.writeValueAsString(result.getData());
                HashMap hashMap = objectMapper.readValue(s, HashMap.class);
                log.debug("hashMap = " + hashMap);
                String jwt = JwtUtil.createJWT(30, hashMap);
                log.debug("jwt = " + jwt);
                cxt.getResponse().addHeader("Authorization", jwt);
            }
            cxt.getResponse().setContentType("application/json;charset=utf-8");
            // 重新将 result 写入响应对象
            log.debug("json = " + json);
            cxt.setResponseBody(json);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
